﻿using MediatR;
using Newtonsoft.Json;
using Warehouse.Domain.DTO;
using Warehouse.Read.API.Applcation.Command.BeginFinalCommand;
using static WMSpublic.ParseAPI;
using WMSpublic;
using Warehouse.Infrstructre.Interface;
using Org.BouncyCastle.Tls.Crypto;

namespace Warehouse.Read.API.Applcation.CommandHandlers.BeginFinalCommandHandler
{
    public class BeginFinalListCommandHandler : IRequestHandler<BeginFinalListCommand, PageDTO<BeginFinalDto>>
    {
        IWarehouseRepository wRep;   //仓库
        IOutProductRepository opRep; //出库
        IEnterStoragesInfoRepsitory esRep;  //入库

        public BeginFinalListCommandHandler(IWarehouseRepository wRep,
        IOutProductRepository opRep,
        IEnterStoragesInfoRepsitory esRep)
        {
            this.wRep = wRep;
            this.opRep = opRep;
            this.esRep = esRep;
        }

        public async Task<PageDTO<BeginFinalDto>> Handle(BeginFinalListCommand request, CancellationToken cancellationToken)
        {
            List<Products> products = await GetProductsList(1, 1000);
            var wData = await wRep.GetAllAsyns();  // 获取仓库数据
            var opData = await opRep.GetAllAsyns();  // 获取出库数据
            var esData = await esRep.GetAllAsyns();  // 获取入库数据

            //计算期初
            //var result = from p in products
            //             join w in await wRep.GetAllAsyns() on p.WarehouseId equals w.WarehouseId
            //             where p.AddTime > new DateTime(2024, 11, 11) && w.WarehouseId == p.WarehouseId
            //             group p by p.AddTime into g   // 新分组叫g
            //             select new
            //             {
            //                 AddTime = g.Key,
            //                 TotalProcurementNum = g.Sum(x => x.ProcurementNum ?? 0) //通过时间分组后的求和
            //             };

            var list = from p in products
                        join w in wData on p.WarehouseId equals w.WarehouseId
                        join op in opData on p.ProductsID equals op.ProductsID
                        join es in esData on p.ProductsID equals es.ProductsID
                        let procurementData = (from p2 in products
                                               join w2 in wData on p2.WarehouseId equals w2.WarehouseId
                                               where p2.AddTime > new DateTime(2024, 11, 11) && w2.WarehouseId == p2.WarehouseId
                                               group p2 by p2.AddTime into g
                                               select new
                                               {
                                                   AddTime = g.Key,
                                                   TotalProcurementNum = g.Sum(x => x.ProcurementNum ?? 0)
                                               }).FirstOrDefault(x => x.AddTime == p.AddTime)
                        select new BeginFinalDto
                        {
                            AddTime = p.AddTime,
                            ProductsID = p.ProductsID,
                            ProductsName = p.ProductsName,
                            ProductsCode = p.ProductsCode,
                            Specs = p.Specs,
                            ProductTypeID = p.ProductTypeID,
                            StorageUnits = p.StorageUnits,
                            WarehouseId = w.WarehouseId,
                            WarehouseName = w.WarehouseName,
                            Result = procurementData?.TotalProcurementNum ?? 0,  //没有找到返回0
                            Quantity = es.Quantity,
                            OutProuductNum = op.OutProuductNum
                        };
            if (!string.IsNullOrEmpty(request.ProductsCode))
            {
                list = list.Where(c => c.ProductsCode.Contains(request.ProductsCode));
            }
            if (!string.IsNullOrEmpty(request.ProductsName))
            {
                list = list.Where(c => c.ProductsName.Contains(request.ProductsName));
            }
            if (request.WarehouseId != 0)
            {
                list = list.Where(c => c.WarehouseId == request.WarehouseId);
            }

            PageDTO<BeginFinalDto> page = new PageDTO<BeginFinalDto>();
            page.Totalcount = list.Count();
            page.Pagecount = (int)Math.Ceiling(page.Totalcount * 1.0 / (int)request.Psize);
            page.list = list.OrderByDescending(x => x.ProductsID).Skip((request.Pindex - 1) * request.Psize).Take(request.Psize).ToList();

            return page;
        }


        /// <summary>
        /// 产品
        /// </summary>
        /// <returns></returns>
        public async Task<dynamic> GetProductsList(int pindex, int psize)
        {
            string token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIyNiIsInNpZCI6IjE4NTk4MDM1MDY2MzA4NTY3MDQiLCJodHRwOi8vc2NoZW1hcy5taWNyb3NvZnQuY29tL3dzLzIwMDgvMDYvaWRlbnRpdHkvY2xhaW1zL2dyb3Vwc2lkIjoiMiIsImp0aSI6IjQzMzA2NmRmLWYyNjAtNDI2Ny1iYWY5LWJkMzgxZGVhZGMwYiIsImh0dHA6Ly9zY2hlbWFzLnhtbHNvYXAub3JnL3dzLzIwMDUvMDUvaWRlbnRpdHkvY2xhaW1zL25hbWUiOiLku5jmtJvlmIkiLCJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy91cmkiOiIiLCJpc3MiOiJSZW5hb2JvMjAwNCIsImF1ZCI6IldlaWZ1d3UyMjAzQSJ9.JtV8g_mbUcJgyPC793AMsvjLkmkeuiRR9BAH6rQp8aU";
            HttpClientWrapper cilent = new HttpClientWrapper(token);

            string chanpin = "http://116.205.121.197:8000/cpd/api/ProductRead/GetAllProductInfo?pageindex=" + pindex + "&pagesize=" + psize;

            string postReponse = await cilent.GetAsync(chanpin);
            var json = JsonConvert.DeserializeObject<ApiResultList<Products>>(postReponse);
            return json.data.list;
        }


        //产品
        public class Products
        {
            /// <summary>
            /// 添加时间
            /// </summary>
            public DateTime? AddTime { get; set; }

            /// <summary>
            /// 产品id
            /// </summary>
            public int ProductsID { get; set; }
            /// <summary>
            /// 产品编号
            /// </summary>
            public string? ProductsCode { get; set; }
            /// <summary>
            /// 产品名称
            /// </summary>
            public string? ProductsName { get; set; }
            /// <summary>
            /// 厂商编码
            /// </summary>
            public string? VendorsCode { get; set; }
            /// <summary>
            /// 内部编码
            /// </summary>
            public string? InteriorCode { get; set; }
            /// <summary>
            /// 规格
            /// </summary>
            public string? Specs { get; set; }
            /// <summary>
            /// 产品类别
            /// </summary>
            public int? ProductTypeID { get; set; }
            /// <summary>
            /// 存储单位
            /// </summary>
            public string? StorageUnits { get; set; }
            /// <summary>
            /// 预警（上）
            /// </summary>
            public int? Upperlimit { get; set; }
            /// <summary>
            /// 预警（下）
            /// </summary>
            public int? Lowerlimit { get; set; }
            /// <summary>
            /// 包装类型
            /// </summary>
            public int? WrapType { get; set; }
            /// <summary>
            /// 价格
            /// </summary>
            public decimal? Price { get; set; }
            /// <summary>
            /// 重量
            /// </summary>
            public decimal? Weight { get; set; }
            /// <summary>
            /// 默认仓库
            /// </summary>
            public int? WarehouseId { get; set; }
            /// <summary>
            /// 库位
            /// </summary>
            public int? StorehouseId { get; set; }
            /// <summary>
            /// 默认供应商
            /// </summary>
            public int? VendorId { get; set; }
            /// <summary>
            /// 默认客户
            /// </summary>
            public int? ClientId { get; set; }
            /// <summary>
            /// 描述
            /// </summary>
            public string? Describe { get; set; }
            /// <summary>
            /// 产品数量
            /// </summary>
            public int? ProcurementNum { get; set; }
            /// <summary>
            /// 公司id
            /// </summary>
            public string? Office_Id { get; set; }

            /// <summary>
            /// 用户id
            /// </summary>
            public int? User_Id { get; set; }
        }

    }
}
